import Vue from 'vue'
import VueRouter from 'vue-router'
import MainLayout from '@/layouts/MainLayout.vue'
import ElementUI from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: MainLayout,
    redirect: '/login',
    children: [
      {
        path: '/login',
        name: 'login',
        component: () => import('@/views/enterprise/EnterpriseLogin.vue')
      },
      {
        path: '/jobs',
        name: 'JobManagement',
        component: () => import('@/views/enterprise/JobManagement.vue'),
        meta: { requiresAuth: true, title: '招聘管理' }
      },
      {
        path: '/forum',
        name: 'Forum',
        component: () => import('@/views/forum/ForumList.vue'),
        meta: { requiresAuth: true, title: '论坛交流' }
      },
      {
        path: '/evaluation',
        name: 'Evaluation',
        component: () => import('@/views/evaluation/EvaluationList.vue'),
        meta: { requiresAuth: true, title: '学生评价' }
      },
      {
        path: '/enterprise/register',
        name: 'EnterpriseRegister',
        component: () => import('@/views/enterprise/EnterpriseRegister.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 判断该路由是否需要登录权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      ElementUI.Message.warning(`请先登录后再访问${to.meta.title}`)
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    // 如果已登录且访问登录页，重定向到首页
    if (token && to.path === '/login') {
      next('/jobs')
    } else {
      next()
    }
  }
})

export default router 